﻿using Loong.Admin.ExceptionHandling;
using Loong.Admin.Results;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;

namespace Loong.Admin
{
    public static class MvcExtensions
    {
        public static MvcOptions AddActionFilters(this MvcOptions options)
        {
            options.Filters.AddService(typeof(AdminResultFilter));
            options.Filters.ReplaceService<AbpExceptionFilter, AdminExceptionFilter>();

            return options;
        }

        public static void ReplaceService<TFilter, TNewFilter>(this FilterCollection filters)
            where TFilter : IFilterMetadata
            where TNewFilter : IFilterMetadata
        {
            ReplaceService(filters, typeof(TFilter), typeof(TNewFilter));
        }

        public static void ReplaceService(this FilterCollection filters, Type filterType, Type newFilterType)
        {
            filters.RemoveService(filterType);
            filters.AddService(newFilterType);
        }

        public static void RemoveService(this FilterCollection filters, Type filterType)
        {
            filters.RemoveAll(f => f is ServiceFilterAttribute serviceFilter && filterType.IsAssignableFrom(serviceFilter.ServiceType));
        }
    }
}
